const fetch = require("../../utils/fetch");
const app = getApp();
let mta = require("../../utils/mta_analysis");
Page({
  data: {
    payType: 1, //支付方式1->微信支付；4->余额支付
    code: "", //订单号，从待付款订单进入·的会在路由上携带订单号
    obj: "", //订单的商品信息或者购物车信息
    balance: 0, //余额
    promotionPrice: 0, //最终需要实际支付的金额
    // isBind: false,//用户是否绑定了手机号，未绑定时不予显示余额支付的选项
    template: "", //my_toast
    my_toast_tip: "",
    imageUrl: app.globalData.imageUrl,
    from: "",
    vipLevel: "注册会员",
    autoFlag: "", //1.无优惠券2.没有符合优惠券3.有符合条件优惠券，
    balanceSignStatus: 0, //0：未签约,有密码  1：已签约  2:未签约,没密码
    isShow: false,
    input_type: true,
    styleList: [
      "noSelect_style",
      "noSelect_style",
      "noSelect_style",
      "noSelect_style",
      "noSelect_style",
      "noSelect_style"
    ],
    supportMx: "3",
    mxCheaper: "",
    mxSavingAmount: "",
    mxDisountRate: "",
    isNeedwx: false
  },

  onShow: function() {
    this.getShopName();
    // this.setData({
    //   shopType: app.globalData.common.shopType
    // });
    this.canPay = true;
    if (!this.data.code) {
      this.getOrderByCart();
    }
    this.getLevel();

    if (getApp().globalData.userInfo.nickName == "亲") {
      this.setData({
        isNeedwx: true
      });
    }
  },
  getShopName: function() {
		if (!getApp().globalData.common.shopCode) {
			this.setData({
				shopName: "请扫店铺二维码"
			})
			return
		}
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/shop/getShop.do',
			data: {
				shopCode: getApp().globalData.common.shopCode || '',
			},
			header: getApp().globalData.header,
			success: function(res) {
				if (res.data.code == 200) {
          _self.setData({
              shopType: res.data.obj.shopType
            });
            console.log("门店类型————"+_self.data.shopType);
            if(_self.data.shopType==10){
              _self.RongShengCoinBalance();
            }
				} else if (res.data.code == 507) {
					_self.setData({
						shopName: '门店歇业'
					});
				} else {
					_self.setData({
						shopName: '没有该门店'
					});
				}
			}
		})
	},
  RongShengCoinBalance() {
    //请求去参数
    let parameter = {
      url:
        getApp().globalData.baseUrl + "/applet/pay/getRongShengCoinBalance.do",
      data: {
        phone: ""
      }
    };
    //请求
    getApp()
      .getRequest(parameter)
      .then(res => {
        this.setData({
          rongsheng: res.data.obj
        });
        //console.log(this.data.rongsheng);
      })
      .catch(err => {
        this.setData({
          rongsheng: err.obj
        });
      });
  },
  freePayStatus: function() {
    //this.canPay = true;
    //查询余额签约状态
    fetch
      .freePayStatus()
      .then(response => {
        console.log("freePayStatus", response);
        this.setData({
          balanceSignStatus: response.data.obj.BALANCE
        });
        if (response.data.obj.BALANCE == 0) {
          this.setData({
            isShow: true,
            styleList: [
              "noSelect_style",
              "noSelect_style",
              "noSelect_style",
              "noSelect_style",
              "noSelect_style",
              "noSelect_style"
            ]
          });
        } else {
          this.doPay();
        }
      })
      .catch(error => {
        console.log("freePayStatuserror", error);
        fetch.showMyToast(this, error.data.des);
      });
  },
  getOrderByCart: function() {
    fetch.loadingText({
      title: "加载中",
      mask: true
    });
    fetch
      .getCartV1(
        app.globalData.common.voucherMemberId,
        app.globalData.common.isAuto
      )
      .then(response => {
        fetch.hideLoadingText();
        const res = response.data;
        console.log("*******");
        console.log(res);
        if (res.code == 200) {
          if (!res.obj.haveGoods) {
            wx.showToast({
              title: "空空如也~",
              image: "../../image/warn.png",
              duration: 1000,
              complete: function() {
                wx.redirectTo({
                  url: "../scan/scan"
                });
              }
            });
            return;
          }
          this.setData({
            obj: res.obj,
            promotionPrice: res.obj.promotionPrice,
            autoFlag: res.obj.autoFlag,
            supportMx: res.obj.supportMx,
            mxCheaper: res.obj.mxCheaper,
            mxSavingAmount: res.obj.mxSavingAmount,
            mxDisountRate: res.obj.mxDisountRate,
            showCouponPrice: res.obj.showCouponPrice,
            vipsavingPrice: res.obj.vipsavingPrice,
            supportMx: res.obj.supportMx
          });
          app.globalData.common.voucherMemberId =
            this.data.obj.voucherMemberId == null
              ? ""
              : this.data.obj.voucherMemberId;
          console.log(app.globalData.common.voucherMemberId);
          this.getBalance();
        }
      })
      .catch(err => {
        fetch.hideLoadingText();
        console.log(err);
        fetch.showMyToast(this, err.data.des);
      });
  },
  getOrderByCode: function(code) {
    fetch.loadingText({
      title: "加载中",
      mask: true
    });
    fetch
      .getOrderByCode(code)
      .then(response => {
        fetch.hideLoadingText();
        const res = response.data;

        if (res.code == 200) {
          let newObj = this.reziseObj(res.obj);

          this.setData({
            obj: newObj,
            promotionPrice: newObj.promotionPrice
          });
          console.log("test", this.data.obj);
          this.getBalance();
          // this.autoSelect();
        }
      })
      .catch(err => {
        fetch.hideLoadingText();
        fetch.showMyToast(this, err.data.des);
      });
  },
  getBalance: function() {
    // 获取余额
    fetch
      .getBalance()
      .then(response => {
        const res = response.data;
        this.setData({
          balance: res.obj.balance
        });
        this.autoSelect();
      })
      .catch(err => {
        fetch.hideLoadingText();
        fetch.showMyToast(this, err.data.des);
      });
  },
  autoSelect: function() {
    const { promotionPrice, balance } = this.data;

    if (promotionPrice == 0) {
      // console.log('0')
      this.setData({
        payType: 4
      });
      return;
    }

    // console.log(promotionPrice, balance,promotionPrice > balance)
    const payType = Number(promotionPrice) > Number(balance) ? 1 : 4;
    this.setData({
      payType: payType
    });
  },
  select_pay: function(event) {
    const type = event.currentTarget.dataset.type;
    // console.log(type);
    const { promotionPrice, balance, rongsheng } = this.data;

    if (promotionPrice == 0) {
      this.setData({
        payType: 4
      });
      wx.showToast({
        title: "请使用余额支付",
        image: "../../image/warn.png",
        duration: 1000
      });
      return;
    }
    // console.log(type);
    if (type == 10) {
      if (Number(promotionPrice) > Number(rongsheng)) {
        wx.showToast({
          title: "余额不足",
          image: "../../image/warn.png",
          duration: 1000
        });
        return;
      }
    }
    if (type == 4) {
      //余额不足时,只能微信支付1
      if (Number(promotionPrice) > Number(balance)) {
        this.setData({
          payType: 1
        });
        wx.showToast({
          title: "余额不足",
          image: "../../image/warn.png",
          duration: 1000
        });
        return;
      }
    }
    this.setData({
      payType: type
    });
  },
  /**
   */
  formSubmit: function(e) {
    console.log("e.detail.formId");
    console.log(e.detail.formId);
    this.setData({
      formId: e.detail.formId
    });
    //if(app.globalData.common.shopType==10&&this.data.rongsheng>this.data.promotionPrice){
    this.doValite();
    // }
  },

  doValite: function() {
    if (!this.canPay) {
      return;
    }
    this.canPay = false;
    const { payType, code, balanceSignStatus } = this.data;
    if (payType == 4) {
      //查询签约状态
      this.freePayStatus();
    } else {
      this.doPay();
    }
  },
  doPay: function() {
    // this.canPay = true;
    const { payType, code, balanceSignStatus } = this.data;

    fetch.loadingText({
      title: "加载中",
      mask: true
    });
    //如果订单号已经存在，则是由待付款订单进入的，直接调用支付接口，否则要先创建订单
    console.log(payType, code);

    if (!code) {
      fetch
        .createOrder(app.globalData.common.voucherMemberId, this.data.formId)
        .then(response => {
          app.globalData.common.voucherMemberId = "";
          app.globalData.common.isAuto = "";
          fetch.hideLoadingText();
          const res = response.data;
          if (res.code == 200) {
            this.setData({
              code: res.obj
            });
            this.wxPay();
          } else {
            this.canPay = true;
          }
        })
        .catch(err => {
          app.globalData.common.voucherMemberId = "";
          app.globalData.common.isAuto = "";
          fetch.hideLoadingText();
          fetch.showMyToast(this, err.data.des);
        });
    } else {
      this.wxPay();
    }
  },
  wxPay: function() {
    var that = this;
    fetch.loadingText({
      title: "加载中",
      mask: true
    });
    fetch
      .newgetPayParams(this.data.code, this.data.payType)
      .then(response => {
        fetch.hideLoadingText();
        const res = response.data;
        // 支付方式为微信无密码支付时
        if (res.code == 200 && this.data.payType == 1 && res.obj.type == 1) {
          //免密支付成功 status=1
          if (res.obj.status == 1) {
            fetch
              .showToast({
                title: "微信代扣成功",
                icon: "success",
                duration: 2000,
                mask: true
              })
              .then(response => {
                //  wx.reLaunch在小程序进入后台后，无法运行，余额支付时，不需要调用微信支付，所以可用
                app.globalData.common.selfPay = 1;
                wx.redirectTo({
                  url: `../fulfil/fulfil?type=0&orderCode=${
                    res.obj.orderCode
                  }&discountPrice=${res.obj.discountPrice}&orderPrice=${
                    res.obj.orderPrice
                  }&from=${that.data.from}`
                });
              })
              .catch(err => {
                fetch.showMyToast(that, err.data.des);
                app.globalData.common.selfPay = 1;
                wx.redirectTo({
                  url: "../orders/orders?current=0"
                });
              });
          } else if (res.obj.status == 4) {
            //免密支付 status=4  支付中   status=2 免密支付失败
            fetch
              .showToast({
                title: "请稍候查看订单状态",
                icon: "none",
                duration: 2000,
                mask: true
              })
              .then(response => {
                //  wx.reLaunch在小程序进入后台后，无法运行，余额支付时，不需要调用微信支付，所以可用
                wx.redirectTo({
                  url: "../orders/orders?current=0"
                });
              });
          } else {
            wx.showModal({
              title: "支付异常",
              content: res.obj.msg,
              confirmText: "重新下单",
              success: function(res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: "../scan/scan"
                  });
                } else if (res.cancel) {
                  wx.redirectTo({
                    url: "../orders/orders?current=0"
                  });
                }
              }
            }); // 支付方式为微信有密码支付时
          }
        } else if (
          res.code == 200 &&
          this.data.payType == 1 &&
          res.obj.type == 0
        ) {
          wx.requestPayment(
            {
              timeStamp: res.obj.timeStamp,
              nonceStr: res.obj.nonceStr,
              package: res.obj.prepay_id,
              signType: res.obj.signType,
              paySign: res.obj.paySign,
              success: function(response) {
                fetch.showToast({
                  title: "支付成功",
                  icon: "success",
                  duration: 2000,
                  mask: true
                });
                app.globalData.common.selfPay = 1;
                // wx.switchTab({     url:'../mine/mine' })
                wx.redirectTo({
                  url: `../fulfil/fulfil?type=0&orderCode=${
                    res.obj.orderCode
                  }&discountPrice=${res.obj.discountPrice}&orderPrice=${
                    res.obj.orderPrice
                  }&from=${that.data.from}`
                });
              },
              fail: function(res) {
                console.log(res);
                //  fetch.showMyToast(that, res.errMsg)
                app.globalData.common.selfPay = 1;
                wx.redirectTo({
                  url: "../orders/orders?current=0"
                });
              }
            } // 支付方式为余额支付时
          );
        } else if (
          res.code == 200 &&
          this.data.payType == 4 &&
          res.obj.code == "4"
        ) {
          console.log("余额支付");
          console.log(res);
          mta.Event.stat("smg_btyijandenglu", {});
          fetch
            .showToast({
              title: "余额支付成功",
              icon: "none",
              duration: 2000,
              mask: true
            })
            .then(response => {
              //  wx.reLaunch在小程序进入后台后，无法运行，余额支付时，不需要调用微信支付，所以可用
              app.globalData.common.selfPay = 1;
              wx.redirectTo({
                url: `../fulfil/fulfil?type=0&orderCode=${
                  res.obj.orderCode
                }&discountPrice=${res.obj.discountPrice}&orderPrice=${
                  res.obj.orderPrice
                }&from=${that.data.from}`
              });
            })
            .catch(err => {
              fetch.showMyToast(that, err.data.des);
              app.globalData.common.selfPay = 1;
              wx.redirectTo({
                url: "../orders/orders?current=0"
              });
            });
          //荣盛币支付
        } else if (
          res.code == 200 &&
          this.data.payType == 10 &&
          res.obj.code == "10"
        ) {
          if (res.obj.data != null) {
            getApp().globalData.common.passwordAddress = res.obj.data;
            console.log(getApp().globalData.common.passwordAddress);
            wx.redirectTo({
              url: "../webView/webView?url=" + res.obj.data
            });
          } else {
              wx.showToast({
                //title: res.obj.msg,
                title: "当前门店未开通荣盛币支付",
                icon: "none",
                duration: 1000
              });
            }
        } else {
          fetch
            .showToast({
              title: res.obj.msg,
              icon: "none",
              duration: 2000,
              mask: true
            })
            .then(response => {
              app.globalData.common.selfPay = 1;
              wx.redirectTo({
                url: "../orders/orders?current=0"
              });
            });
        }
      })
      .catch(err => {
        fetch.hideLoadingText();
        console.log("err", err);
        fetch
          .showToast({
            title: err.data.des,
            icon: "none",
            duration: 20000,
            mask: true
          })
          .then(response => {
            app.globalData.common.selfPay = 1;
            // wx.switchTab({     url: '../mine/mine' })
          });
      });
  },
  reziseObj: function(obj) {
    let newObj = {
      originalPrice: "",
      promotionPrice: "",
      num: 1,
      cartItems: []
    };
    newObj.originalPrice = obj.originalPrice;
    newObj.promotionPrice = obj.price;
    newObj.num = obj.num;
    newObj.vipsavingPrice = obj.vipsavingPrice;
    newObj.couponPrice = obj.couponPrice;

    obj.orderGoods.forEach(ele => {
      console.log("promotionType", ele.promotionType);
      newObj.cartItems.push({
        goods: {
          imgUrl: ele.imagePath,
          goodsName: ele.goodsName,
          originalPrice: ele.originalPrice,
          price: ele.price,
          promotionnName: ele.promotionnName,
          promotionAlias: ele.promotionAlias
        },
        promotionType: ele.promotionType,
        promotionName: ele.promotionName,
        promotionAlias: ele.promotionAlias,
        goodsName: ele.goodsName,
        num: ele.num
      });
    });

    return newObj;
  },
  getLevel: function() {
    //获取用户等级
    fetch.loadingText(),
      fetch
        .getLevel()
        .then(response => {
          fetch.hideLoadingText();
          const res = response.data;
          if (res.code == 200) {
            this.vip_Level(res.obj.level);
          } else {
            reject(res);
          }
        })
        .catch(e => {
          fetch.hideLoadingText();
          fetch.showMyToast(this, e.data.des);
        });
  },
  vip_Level: function(level) {
    switch (level) {
      case "00":
        this.setData({
          vipLevel: "注册会员"
        });
        break;
      case "01":
        this.setData({
          vipLevel: "青铜会员"
        });
        break;
      case "02":
        this.setData({
          vipLevel: "白银会员"
        });
        break;
      case "03":
        this.setData({
          vipLevel: "黄金会员"
        });
        break;
      case "04":
        this.setData({
          vipLevel: "钻石会员"
        });
        break;
      default:
        this.setData({
          vipLevel: "注册会员"
        });
    }
  },
  goSelect: function() {
    console.log(this.data.obj.autoFlag);
    if (this.data.code) {
      return;
    }
    if (this.data.obj.autoFlag == 1) {
      return;
    }
    wx.navigateTo({
      url: `../selectCoupon/selectCoupon?voucherMemberId=${
        this.data.obj.voucherMemberId
      }`
    });
  },
  onLoad: function(options) {
    console.log();
    mta.Page.init();
    const code = options.code;
    if (code) {
      this.setData({
        code: code,
        from: "mine"
      });

      this.getOrderByCode(code);
    }
  },
  getPassWord: function(e) {
    var _self = this;
    console.log(e.detail.value.length);

    var arr = _self.data.styleList;
    for (var i = 0; i < 6; i++) {
      if (i <= e.detail.value.length - 1) {
        arr[i] = "select_style";
      } else {
        arr[i] = "noSelect_style";
      }
    }
    if (e.detail.value.length == 6) {
      _self.filterPassword(e.detail.value);
    }
    _self.setData({
      styleList: arr
    });
    console.log(_self.data.styleList);
  },
  hideView: function() {
    this.setData({
      input_type: true
    });
  },
  closeView: function() {
    this.canPay = true;
    this.setData({
      isShow: false,
      balanceStatus: false,
      styleList: [
        "noSelect_style",
        "noSelect_style",
        "noSelect_style",
        "noSelect_style",
        "noSelect_style",
        "noSelect_style"
      ]
    });
  },
  filterPassword: function(num) {
    var _self = this;
    wx.request({
      url:
        getApp().globalData.baseUrl +
        "/applet/balance/pwd/check.do?password=" +
        num,
      method: "post",
      header: getApp().globalData.header,
      success: function(res) {
        if (res.data.code == 200) {
          _self.doPay();
        } else {
          // _self.setData({
          //     balanceStatus: false,
          //     isShow: false,
          //     styleList: [
          //         'noSelect_style',
          //         'noSelect_style',
          //         'noSelect_style',
          //         'noSelect_style',
          //         'noSelect_style',
          //         'noSelect_style'
          //     ]
          // })
          _self.closeView();
          fetch.showMyToast(_self, "密码错误");
          _self.canPay = true;
        }
      }
    });
  },
  //麦享
  goOpenMx: function() {
    var mxUrl = "";
    if (this.data.supportMx == 1) {
      //mxUrl = '../maixiang/maixiang'
      mxUrl = "../maixiangMember/maixiangMember";
    } else {
      mxUrl = "../maixiang/maixiang";
      getApp().globalData.common.mxShopCode = getApp().globalData.common.shopCode;
    }
    wx.navigateTo({
      url: mxUrl
    });
  },
  //开通会员
  maixiangTurn: function() {
    var mxUrl = "../maixiang/maixiang";

    getApp().globalData.common.mxShopCode = getApp().globalData.common.reserveShopCode;
    wx.navigateTo({
      url: mxUrl
    });
  },
  bindGetUserInfo: function(e) {
    //console.log(e.detail.userInfo)
    this.updateMember(e.detail.userInfo.nickName, e.detail.userInfo.avatarUrl);
  },
  updateMember: function(name, img) {
    var _self = this;
    var paramInfo = {
      nickName: name,
      avatar: img
    };
    wx.request({
      url: getApp().globalData.baseUrl + "/wxappletMember/updateMember.do",
      method: "POST",
      data: paramInfo,
      header: getApp().globalData.header,
      success: function(res) {
        console.log(res);
        if (res.data.code == 200) {
          getApp().globalData.userInfo.nickName = name;
          getApp().globalData.userInfo.avatarUrl = img;
          _self.setData({
            isNeedwx: false
          });
        } else {
        }
      },
      fail: function() {
        console.log(1);
      }
    });
  }
});
